import React from 'react';
import { connect } from 'react-redux';
import { Form, Input, Row, Col, Affix, Button, Select, message, Spin } from 'antd';
import menuRoute from 'routes/menuRoute';
import config from 'config';
import httpFetch from 'share/httpFetch';
import baseService from 'share/base.service'
import contractService from 'containers/approve/contract/contract.service';
import Upload from 'components/upload';
import { messages } from 'share/common';
import 'styles/contract/my-contract/new-contract.scss';
import Chooser from 'components/chooser';

const FormItem = Form.Item;
const Option = Select.Option;

class NewContract extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      pageLoading: false,
      record: {
        companyId:props.company.id,
        companyName: props.company.name,
        currency: props.company.baseCurrency
      },
      contractType: {},
      fileList: [],
      user: {},
      isNew: true, //新建 or 编辑
      contractInfo: {}, //编辑的合同信息
      partnerCategoryOptions: [], //合同方类型选项
      currencyOptions: [], //币种
      companySelectorItem: {//公司  ${config.contractUrl}/api/contract/type/${setOfBooksId}/companies/query`
        title: messages('my.contract.contractCompany'/*合同公司*/),
        url: `${config.contractUrl}/api/contract/type/${this.props.company.setOfBooksId}/companies/query?isEnabled=true`,
        searchForm: [
          {
            type: 'input',
            id: 'companyCode',
            label: messages('chooser.data.companyCode'/*公司代码*/)
          },
          {
            type: 'input',
            id: 'companyName',
            label: messages('chooser.data.companyName'/*公司名称*/)
          }
        ],
        columns: [
          {
            title: messages('chooser.data.companyCode'/*公司代码*/),
            dataIndex: 'companyCode'
          },
          {
            title: messages('chooser.data.companyName'/*公司名称*/),
            dataIndex: 'companyName'
          },
          {
            title: messages('chooser.data.companyType'/*公司类型*/),
            dataIndex: 'companyTypeName',
            render: value => value || '-'
          },
        ],
        key: 'id'
      },
      contractCategoryOptions: [], //合同大类选项
      uploadOIDs: [], //上传附件的OIDs
      employeeOptions: [], //员工选项
      venderOptions: [], //供应商选项
      contractCategoryValue: 'EMPLOYEE',
      unitIdOptions: [], //责任部门选项
      employeeIdOptions: [], //责任人选项
      currencyLoading: false,
      extraParams: null,
      contractCategory: undefined,
      departmentId: '',
      myContract: menuRoute.getRouteItem('my-contract', 'key'),    //我的合同
      contractDetail: menuRoute.getRouteItem('contract-detail', 'key'),    //合同详情
    };
  }

  //根据合同类型id获取合同类型
  getContractType = () => {
    contractService.getContractTypeInfo(this.props.company.setOfBooksId, this.props.params.contractTypeId)
      .then(response => {
        this.setState({ contractType: response.data });
      });
  };


  componentWillMount() {
    this.getContractType();
    Number(this.props.params.id) && this.getInfo(); //合同编辑
    this.setState({ user: this.props.user });
    this.getSystemValueList(2107)
      .then(res => { //合同方类型
        let partnerCategoryOptions = res.data.values || [];
        this.setState({ partnerCategoryOptions });
      });
    this.getSystemValueList(2202)
      .then(res => { //合同大类
        let contractCategoryOptions = res.data.values || [];
        this.setState({ contractCategoryOptions });
      });

    //获取责任部门列表 flag = 1001全部, 1002启用, 1003未启用
    httpFetch.get(`${config.baseUrl}/api/departments/root/v2?flag=1001`)
      .then(res => {
        res.status === 200 && this.setState({ unitIdOptions: res.data });
      });
  }

  //获取合同信息
  getInfo = () => {
    this.setState({ pageLoading: true });
    contractService.getContractHeaderInfo(this.props.params.id)
      .then(res => {
        let fileList = [];
        if (res.data.attachments) {
          res.data.attachments.map(item => {
            fileList.push({
              ...item,
              uid: item.attachmentOID,
              name: item.fileName,
              status: 'done',
            });
          });
        }
        this.setState({
          record: res.data,
          isNew: false,
          uploadOIDs: res.data.attachmentOIDs,
          fileList,
          pageLoading: false,
          contractCategoryValue: res.data.partnerCategory,
          contractCategory: res.data.contractCategory,
          extraParams: res.data.companyId,
          departmentId: res.data.unitId
        });
        // res.data.unitId && this.changeUnitId(res.data.unitId, true);
      });
  };

  //获取币种
  getCurrencyOptions = () => {
    this.setState({ currencyLoading: true });
    !this.state.currencyOptions.length && baseService.getAllCurrencyByLanguage()
      .then((res) => {
        let currencyOptions = res.data;
        this.setState({ currencyOptions, currencyLoading: false });
      });
  };

  //上传附件
  handleUpload = (OIDs) => {
    let uploadOIDs = OIDs.join(',');
    this.setState({ uploadOIDs: uploadOIDs });
  };

  //保存
  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.attachmentOIDs = this.state.uploadOIDs.toString();
        values.contractTypeId = this.props.params.contractTypeId;
        values.contractCategory = this.state.contractType.contractCategory;
        values.unitId = this.state.departmentId;
        values.applicantOid = this.props.user.userOID;
        values.companyId = values.companyId && values.companyId[0].companyId;
        this.setState({ loading: true });
        contractService.newContractHeader(values)
          .then(res => {
            if (res.status === 200) {
              this.setState({ loading: false });
              message.success(messages('common.save.success', { name: '' }/*保存成功*/));
              this.context.router.push(this.state.contractDetail.url.replace(':id', res.data.id));
            }
          })
          .catch(e => {
            message.error(`${messages('common.save.filed'/*保存失败*/)}，${e.response.data.message}`);
            this.setState({ loading: false });
          });
      }
    });
  };

  //更新
  handleUpdate = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let params = {
          id: this.state.record.id,
          versionNumber: this.state.record.versionNumber,
          companyId: values.companyId[0].companyId,
          attachmentOIDs: this.state.uploadOIDs.toString(),
          remark: values.remark,
          contractTypeId: this.props.params.contractTypeId
        };
        values.id = this.state.record.id;
        values.companyId = values.companyId && values.companyId[0].companyId;
        values.versionNumber = this.state.record.versionNumber;
        this.setState({ loading: true });
        contractService.updateContractHeader(params)
          .then(res => {
            if (res.status === 200) {
              this.setState({ loading: false });
              message.success(messages('common.save.success', { name: '' }/*保存成功*/));
              this.context.router.push(this.state.contractDetail.url.replace(':id', res.data.id));
            }
          })
          .catch(e => {
            if (!e.response) return;
            message.error(`${messages('common.save.filed'/*保存失败*/)}，${e.response.data.message}`);
            this.setState({ loading: false });
          });
      }
    });
  };

  //取消
  onCancel = () => {
    this.context.router.push(this.state.myContract.url);
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, record, companySelectorItem, pageLoading, contractType, fileList, currencyOptions, currencyLoading } = this.state;

    const rowLayout = { type: 'flex', gutter: 24, justify: 'center' };
    const formItemLayout = {
      labelCol: {
        xs: { span: 14 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      }
    };

    return (
      <div className="new-contract " style={{ marginBottom: '50px' }}>
        <Spin spinning={pageLoading}>
          <Form onSubmit={record.id ? this.handleUpdate : this.handleSave}>
            <Row {...rowLayout}>
              <Col span={10}>
                <FormItem label={messages('contract.createdBy')} {...formItemLayout}>
                  {getFieldDecorator('employeeId', {
                    rules: [{
                      required: true,
                      message: messages('common.please.select')
                    }],
                    initialValue: this.props.user.fullName
                  })(
                    <Select disabled placeholder={messages('common.please.select')} getPopupContainer={triggerNode => triggerNode.parentNode}/>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row {...rowLayout}>
              <Col span={10}>
                <FormItem label={messages('my.contract.type')} {...formItemLayout}> {/*合同类型*/}
                  {getFieldDecorator('contractTypeId', {
                    rules: [{
                      required: true,
                      message: messages('common.please.select')
                    }],
                    initialValue: contractType.contractTypeName
                  })(
                    <Select style={{ width: '100%' }} disabled getPopupContainer={triggerNode => triggerNode.parentNode}
                            placeholder={messages('common.please.select')}/>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row {...rowLayout}>
              <Col span={10}>
                <FormItem label={messages('my.contract.category')} {...formItemLayout}> {/*合同大类*/}
                  {getFieldDecorator('contractCategory', {
                    rules: [{
                      required: true,
                      message: messages('common.please.select')
                    }],
                    initialValue: contractType.contractCategoryName
                  })(
                    <Input style={{ width: '100%' }} disabled
                           placeholder={messages('common.please.enter')}/>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row {...rowLayout}>
              <Col span={10}>
                <FormItem
                  label={messages('my.contract.contractCompany')}{...formItemLayout}>{/*合同公司*/}
                  {getFieldDecorator('companyId', {
                    rules: [{
                      required: true,
                      message: messages('common.please.select')
                    }],
                    initialValue: record.companyId ? [{
                      companyId: record.companyId,
                      companyName: record.companyName
                    }] : []
                  })(
                    <Chooser
                      selectorItem={companySelectorItem}
                      labelKey='companyName'
                      placeholder={messages('common.please.select')}
                      valueKey='companyId'
                      single={true}
                      listExtraParams={{ contractTypeId: this.props.params.contractTypeId }}
                    />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row {...rowLayout}>
              <Col span={10}>
                <FormItem label={messages('common.currency')}{...formItemLayout}>
                  {getFieldDecorator('currency', {
                    rules: [{
                      required: true,
                      message: messages('common.please.select')
                    }],
                    initialValue: record.currency ? record.currency : 'CNY'
                  })(
                    <Select
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                      disabled={!!record.id}
                      placeholder={messages('common.please.select'/*请选择*/)}
                      onFocus={this.getCurrencyOptions}
                      notFoundContent={currencyLoading ?
                        <Spin size="small"/> : messages('my.contract.no.result'/*无匹配结果*/)}>
                      {currencyOptions.map((option) => {
                        return <Option key={option.currency}>{option.currency}</Option>;
                      })}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row {...rowLayout}>
              <Col span={10}>
                <FormItem label={messages('request.detail.jd.remark')} {...formItemLayout}>
                  {getFieldDecorator('remark', {
                    rules: [{
                      required: true,
                      message: messages('common.please.enter')
                    }],
                    initialValue: record.id ? record.remark : ''
                  })(
                    <Input.TextArea placeholder={messages('common.please.enter')}/>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row {...rowLayout}>
              <Col span={10}>
                <FormItem label={messages('acp.fileInfo')} {...formItemLayout}>
                  {getFieldDecorator('attachmentOIDs')(
                    <Upload attachmentType="CONTRACT"
                            uploadUrl={`${config.baseUrl}/api/upload/attachment`}
                            fileNum={9}
                            uploadHandle={this.handleUpload}
                            defaultFileList={fileList}
                            defaultOIDs={this.state.uploadOIDs}/>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Affix offsetBottom={0}
                   style={{
                     position: 'fixed',
                     bottom: 0,
                     marginLeft: '-35px',
                     width: '100%',
                     height: '50px',
                     boxShadow: '0px -5px 5px rgba(0, 0, 0, 0.067)',
                     background: '#fff',
                     lineHeight: '50px'
                   }}>
              <Button type="primary" htmlType="submit" loading={loading}
                      style={{ margin: '0 20px' }}>{messages('my.contract.next')}</Button>
              <Button onClick={this.onCancel}>{messages('common.cancel')}</Button>
            </Affix>
          </Form>
        </Spin>
      </div>
    );
  }
}

NewContract.contextTypes = {
  router: React.PropTypes.object
};

const wrappedNewContract = Form.create()((NewContract));

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company
  };
}

export default connect(mapStateToProps, null, null, { withRef: true })(wrappedNewContract);


